package com.whut.controller;

import com.whut.entity.UserLogin;
import com.whut.service.IUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/user")
public class UserLoginController {
    @Autowired
    private IUserLoginService userService;

    @Value("${pictureFile.path}")
    private String avatarUrl;

    @Value("${pictureFile.path-mapping}")
    private String avatarUrlMapping;

    @PostMapping("/login")
    public UserLogin login(@RequestBody UserLogin user) {
        System.out.println("Received login request: " + user.getUsername());
        return userService.login(user.getUsername(), user.getPassword());
    }

    @PostMapping("/avatarUpload")
    public String uploadAvatar(@RequestParam MultipartFile file) {
        try {
            String fileName = UUID.randomUUID().toString() + "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            // 定义保存路径（建议使用文件系统路径）
//            String savePath = avatarUrl;
//            File saveDir = new File(savePath);
//
//            // 如果目录不存在，则创建
//            if (!saveDir.exists()) {
//                saveDir.mkdirs();
//            }
//
//            // 创建目标文件
//            File destFile = new File(saveDir, fileName);
//
//            // 上传文件
//            file.transferTo(destFile);
//
//            String finalFileName = avatarUrlMapping + fileName;
           // System.out.println("Uploaded avatar URL: " + finalFileName); // 控制台输出上传成功的 URL
           // System.out.println("Saved avatar path: " + path); // 输出保存路径

            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    @PostMapping("/register")
    public boolean register(@RequestPart("user") UserLogin user,
                            @RequestPart("file") MultipartFile file) {
        try {
            //System.out.println("Registered user: " + user); // 输出用户信息
            // 处理头像文件
            if (file != null && !file.isEmpty()) {
                String fileName = UUID.randomUUID().toString() + "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                // 定义保存路径（建议使用文件系统路径）
                String savePath = avatarUrl;
                File saveDir = new File(savePath);

                // 如果目录不存在，则创建
                if (!saveDir.exists()) {
                    saveDir.mkdirs();
                }

                // 创建目标文件
                File destFile = new File(saveDir, fileName);

                // 上传文件
                file.transferTo(destFile);

                String finalFileName = avatarUrlMapping + fileName;
                user.setAvatar(finalFileName); // 设置头像 URL
            }

            // 注册用户
            userService.register(user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @PostMapping("/verifyEmail")
    public String verifyEmail(@RequestParam String email) {
        try {
            //System.out.println("Verifying email: " + email); // 输出用户信息
            // 验证邮箱
            return userService.verifyEmail(email);
        } catch (Exception e) {
            e.printStackTrace();
            return "验证失败！";
        }
    }

    @PutMapping("/updatePassword")
    public ResponseEntity<String> updatePassword(@RequestBody UserLogin user) {
        boolean result = userService.updatePassword(user);
        if (result) {
            return ResponseEntity.ok("密码更新成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("密码更新失败");
        }
    }



}
